package cn.bearspark.user.provider.service.impl;

import cn.bearspark.user.provider.dao.buffer.UserHashBuffer;
import cn.bearspark.user.provider.dao.mapper.UserActiveMapper;
import cn.bearspark.user.provider.dao.mapper.UserBaseMapper;
import cn.bearspark.user.provider.service.UserHappeningService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author f
 */
@Service
public class UserHappeningServiceImpl implements UserHappeningService {

    private final UserActiveMapper userActiveMapper;
    private final UserBaseMapper userBaseMapper;

    private final UserHashBuffer userBuffer;

    public UserHappeningServiceImpl(UserActiveMapper userActiveMapper,
                                    UserBaseMapper userBaseMapper,
                                    UserHashBuffer userBuffer) {
        this.userActiveMapper = userActiveMapper;
        this.userBaseMapper = userBaseMapper;
        this.userBuffer = userBuffer;
    }

    @Override
    public void afterPublishHappening(long userId) {
        // 更新指定用户的最近活跃时间
        userActiveMapper.updateActiveTime(userId, new Date());
        // 给用户的动态数加一
        userBaseMapper.incrHappeningNum(userId);
        // 清理用户缓存热数据
        userBuffer.cleanHot(userId);
    }

    @Override
    public void afterDeleteHappening(long userId, Date lastPubTime) {
        // 更新指定用户的最近活跃时间
        if (lastPubTime != null) {
            userActiveMapper.updateActiveTime(userId, lastPubTime);
        } else {
            // 如果用户之前没有发布过动态，则将其改为用户的创建时间
            userActiveMapper.updateActiveTimeToCreateTime(userId);
        }
        // 清理用户缓存热数据
        userBuffer.cleanHot(userId);
        // 给用户的动态数减一
        userBaseMapper.decrHappeningNum(userId);
    }

    @Override
    public void afterPublishScheduledHappening(Map<Long, Long> userHappeningCntMap) {
        List<Long> updatedUserIdList = new ArrayList<>();

        // 更新用户的动态数
        userHappeningCntMap.forEach((userId, happeningNum) -> {
            if (userBaseMapper.updateHappeningNum(userId, happeningNum) != 0) {
                updatedUserIdList.add(userId);
            }
        });

        // 批量更新用户的最后活跃时间
        if (!updatedUserIdList.isEmpty()) {
            userActiveMapper.updateBatchActiveTime(updatedUserIdList, LocalDateTime.now());
        }
    }
}
